﻿/// <reference path="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1-vsdoc.js" />

var oGetVars = new (function (sSearch) {
	var rNull = /^\s*$/, rBool = /^(true|false)$/i;
	
	function buildValue(sValue) {
		if (rNull.test(sValue)) { return null; }
		if (rBool.test(sValue)) { return sValue.toLowerCase() === "true"; }
		if (isFinite(sValue)) { return parseFloat(sValue); }
		if (isFinite(Date.parse(sValue))) { return new Date(sValue); }
		return sValue;
	}
	
	if (sSearch.length > 1) {
		for (var aItKey, nKeyId = 0, aCouples = sSearch.substr(1).split("&"); nKeyId < aCouples.length; nKeyId++) {
			aItKey = aCouples[nKeyId].split("=");
			this[decodeURIComponent(aItKey[0]).toLowerCase()] = aItKey.length > 1 ? buildValue(decodeURIComponent(aItKey[1].replace(/[+]/g, "%20"))) : null;
		}
	}
})(window.location.search);

var param = function (name) {
	return oGetVars[name.toLowerCase()];
}

var QRL = {
	Preview:		param("Preview") == 1,
	PageUrl:		param("PageUrl"),
	PageTitle:	param("PageTitle"),
	Link:				param("Link"),
	LinkText:		param("LinkText"),
	Selection:	param("Selection"),
	Size:				param("Size") || "400x400"
}

QRL.Content = QRL.Selection || QRL.Link || QRL.PageUrl;

var updateQR = function (selector, content, size) {
	var src = "https://chart.googleapis.com/chart?choe=UTF-8&cht=qr&chld=Q|0&chs=";
	src += size || (QRL.Preview ? "220x220" : QRL.Size);
	src += "&chl=" + encodeURIComponent(content || QRL.Content);
	$(selector || "#imgQR").attr("src", src);
}


$(document).ready(function () {
	var installed = true;

	if (!QRL.Preview && $.browser && $.browser.msie && $.browser.version >= 8 && window.external && !window.external.IsServiceInstalled(window.location.protocol + "//" + window.location.host, "Encode"))
		installed = false;

	if (!QRL.Preview && !installed) {
		$("#installIE").show().click(function () {
			var addr = window.location.href.replace(/[^/]*$/, "registerIE.ashx");
			window.external.AddService(addr);
			return false;
		});

	}

	if (QRL.Preview) {
		$(".FullMode").hide();
	}
	else {
		$("#Content").text(QRL.Content);

		$("a.Size").click(function () { QRL.Size = $(this).text(); updateQR(); return false; });

		$("#Update").click(function () {
			QRL.Content = $("#Content").val();
			updateQR();
		});

		updateQR("#homeQR", "http://qrl.codeplex.com", "100x100");
	}

	updateQR();
});

